from vartela import Ui_variaveis
from variaveis import Variaveis
from PyQt4 import QtCore, QtGui

class Variaveisui(QtGui.QDialog):
    def __init__(self, pasta, nome, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_variaveis()
        self.ui.setupUi(self)
        #QtCore.QObject.connect(self.ui.bteste1, QtCore.SIGNAL("clicked()"), self.teste1)
        QtCore.QObject.connect(self.ui.btsair, QtCore.SIGNAL("clicked()"), self.close)
        QtCore.QObject.connect(self.ui.btsair_gravar, QtCore.SIGNAL("clicked()"), self.sair_gravar)
        QtCore.QObject.connect(self.ui.btnova, QtCore.SIGNAL("clicked()"), self.criarnova)
        QtCore.QObject.connect(self.ui.btcancelar, QtCore.SIGNAL("clicked()"), self.cancelar)
        QtCore.QObject.connect(self.ui.btremover, QtCore.SIGNAL("clicked()"), self.remover)
        #QtCore.QObject.connect(self.ui.tabela, QtCore.SIGNAL("cellChanged(0,0)"), self.habilitarCancelar)
        #self.ui.btcancelar.setEnabled(False)
        #self.ui.bteste1.setEnabled(False)
        self.ui.tabela.setColumnWidth(0,200)
        self.ui.tabela.setColumnWidth(1,200)

        self.vars = Variaveis(pasta, nome)
        self.abrirvariaveis()

    def habilitarCancelar(self):
        print 'oh eu aki mae'
        self.ui.btcancelar.setEnabled(True)

    def sair_gravar(self):
        self.gravar()
        self.close()

    def cancelar(self):
        self.abrirvariaveis()

    def remover(self):
        self.ui.tabela.removeRow(self.ui.tabela.currentRow())

    def criarnova(self):
        indice = self.ui.tabela.rowCount()
        self.ui.tabela.insertRow(indice)
        self.ui.tabela.setCurrentCell(indice,0)

    def teste1(self):
        print self.ui.tabela.isSortingEnabled()

    def abrirvariaveis(self):
        variaveis , valores = self.vars.carregar()
        qnt = len(variaveis)
        self.ui.tabela.setRowCount(qnt)
        for i in range(qnt):
            variavel = QtGui.QTableWidgetItem(variaveis[i])
            valor = QtGui.QTableWidgetItem(valores[i])
            self.ui.tabela.setItem(i,0,variavel)
            self.ui.tabela.setItem(i,1,valor)
        
    def gravar(self):
        variaveis = []
        valores = []
        qnt = self.ui.tabela.rowCount()
        for i in range(qnt):
            try:
                variavel = self.ui.tabela.item(i,0).text()
                valor =  self.ui.tabela.item(i,1).text()
            except Exception, e:
                print e
                variavel = valor = ''
            if variavel and valor:
                variaveis.append(str(variavel))
                valores.append(str(valor))
        self.vars.gravar(variaveis,valores)

    #def done(self, inteiro):
        #reimplemtacao do metodo
        #self.gravar()
        #QtGui.QDialog.done(self,inteiro)
